<?php

namespace App\Common\Librarys;

use Hyperf\HttpServer\Response;

class ApiResponse
{
    /**
     * @var Response
     */
    protected $apiResponse;

    public function __construct()
    {
        $this->apiResponse = new Response();
    }

    /**
     * @param $data
     * @param $code
     * @param $msg
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function success($data = null, $code = 0, $msg = 'success')
    {
        return $this->apiResponse->json([
            'code' => $code,
            'data' => $data,
            'msg' => $msg
        ]);
    }

    /**
     * 输出失败
     * @param string|array $msg
     * @param $code
     * @param null $data
     * @return ApiResponse
     */
    public static function fail($msg, $code = 10001, $data = null)
    {
        if (is_array($msg) && is_null($code)) {
            $code = $msg[0];
            $msg = $msg[1];
        }

        if ($code == 0) {
            $code = -1;
        }
        // 统一修复错误的时候转义一些前端可能会执行的html标签和方法
        $msg = htmlspecialchars($msg);
        return new self($code, $data, $msg);
    }
}